package com.starblink.message.messagelikeorcomment.ui

import android.content.Context
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.chad.library.adapter.base.BaseQuickAdapter
import com.starblink.android.basic.base.activity.BaseTVMActivity
import com.starblink.android.basic.bean.LoadAction
import com.starblink.android.basic.ext.toast
import com.starblink.android.basic.extension.navigationTo
import com.starblink.android.basic.modules.mine.MineManager
import com.starblink.android.basic.user.UserDataCenter
import com.starblink.basic.log.SKLogger
import com.starblink.basic.route.RoutePage
import com.starblink.basic.style.title.OnTitleBarListener
import com.starblink.basic.style.title.TitleBar
import com.starblink.comment.ui.PostCommentDialog
import com.starblink.message.R
import com.starblink.message.Constants
import com.starblink.message.databinding.ActivityMessageLikeOrCommentBinding
import com.starblink.message.messagelikeorcomment.adapter.MessageLikeOrCommentAdapter
import com.starblink.rocketreserver.FetchUserMessagesV2Query

/**
 * 喜欢消息页和评论消息页复用同一页面
 */
@Route(path = RoutePage.Message.MESSAGE_LIKE_OR_COMMENT)
class MessageLikeOrCommentActivity :
    BaseTVMActivity<ActivityMessageLikeOrCommentBinding, MessageLikeOrCommentVM>() {
    private val mAdapter = MessageLikeOrCommentAdapter()

    @Autowired(name = EXTRA_IS_LIKE_MESSAGE)
    @JvmField
    var isLikeMessage: Boolean = true

    override fun initViewBinding(): ActivityMessageLikeOrCommentBinding =
        ActivityMessageLikeOrCommentBinding.inflate(layoutInflater)

    override fun initView() {
        super.initView()
        viewBinding.titleBar.setTitle(
            if (isLikeMessage) com.starblink.basic.style.R.string.like
            else com.starblink.basic.style.R.string.comments
        )
        viewBinding.titleBar.setOnTitleBarListener(object : OnTitleBarListener {
            override fun onLeftClick(titleBar: TitleBar?) {
                finish()
            }
        })

        viewBinding.recyclerView.layoutManager = LinearLayoutManager(this)
        viewBinding.recyclerView.setHasFixedSize(true)
        viewBinding.recyclerView.itemAnimator = null
        viewBinding.recyclerView.adapter = mAdapter
        mAdapter.setEmptyViewLayout(this, R.layout.layout_empty_view_message)

        viewBinding.smartRefreshLayout.setEnableAutoLoadMore(true)
        viewBinding.smartRefreshLayout.setOnRefreshListener {
            viewModel.getUserMessageList(refresh = true, isLikeMessage)
        }
        viewBinding.smartRefreshLayout.setOnLoadMoreListener {
            viewModel.getUserMessageList(refresh = false, isLikeMessage)
        }

        initClickEvent()
    }

    private fun initClickEvent() {
        // 点击头像，名字, 跳转用户个人中心
        val listener: BaseQuickAdapter.OnItemChildClickListener<FetchUserMessagesV2Query.FetchUserMessagesV2> =
            BaseQuickAdapter.OnItemChildClickListener { adapter, view, position ->
                adapter.getItem(position)?.friend?.let {
                    MineManager.navigationToOtherUserPersonHome(
                        mContext,
                        accountId = it.id,
                        accountDeleted = it.deleted,
                        userName = it.username ?: it.userName
                    )
                }
            }
        mAdapter.addOnItemChildClickListener(R.id.tv_user_name, listener)
        mAdapter.addOnItemChildClickListener(R.id.iv_user_head, listener)

        // 点击图片
        mAdapter.addOnItemChildClickListener(R.id.iv_post_main_pic) { adapter, view, position ->
            val item = adapter.getItem(position)
            item?.apply {
                ///判断账号有没有被删除注销
                if (friend.deleted == true) {
                    toast(com.starblink.basic.style.R.string.account_deleted)
                    return@addOnItemChildClickListener
                }

                /// 先判断内容删除情况
                if (postComment?.post?.postF?.deleted == true) {
                    toast("The content has been deleted.")
                    return@addOnItemChildClickListener
                }

                /// 判断回复评论的状态
                if ((messageType == Constants.MessageType.REPLY_COMMENT && postComment?.deleted == true)
                    || postComment?.user?.accountF?.deleted == true
                ) {
                    toast("The comment has been deleted.")
                    return@addOnItemChildClickListener
                }

                /// 判断 私有并且不是自己的 跳转空页面
                if (postComment?.post?.postF?.privateStatus == true &&
                    postComment?.post?.postF?.posterInfo?.poster?.id != UserDataCenter.getAccountInfo()?.id
                ) {
                    navigationTo(RoutePage.Post.PAGE_CONTENT_DELETED) {
                        withString(
                            RoutePage.Post.ARGS_TIP,
                            "This content cannot be viewed for author set privacy."
                        )
                    }
                    return@addOnItemChildClickListener
                }

                // 打开Post Detail页面
                var post = if (messageType == Constants.MessageType.LIKE_CONTENT) post?.postF
                else postComment?.post?.postF
                post?.run {
                    if (post.deleted == true) {
                        SKLogger.e("dss", "post.deleted == true")
                        navigationTo(RoutePage.Post.PAGE_CONTENT_DELETED) {
                        }
                        return@addOnItemChildClickListener
                    }
                    // 达人相关
//                if (post.sourceType == 3) {
//                    return AppraisalDetail(aid: post.id);
//                }

                    navigationTo(
                        if (contentType == "1") RoutePage.Post.PAGE_PIC  //图文详情
                        else RoutePage.PostVideo.PAGE_VIDEO  //视频详情
                    ) {
                        withInt(RoutePage.Post.ARG_SCENE, RoutePage.Post.SCENE.ME.value)
                        withString(RoutePage.Post.POST_ID, post.id)
                    }
                }
            }
        }

        // 点击回复按钮
        mAdapter.addOnItemChildClickListener(R.id.layout_reply) { adapter, view, position ->
            val item = adapter.getItem(position)
            if (item == null || item.postComment?.post?.postF?.id == null) {
                return@addOnItemChildClickListener
            }

            val dialog = PostCommentDialog(this, com.starblink.android.basic.R.style.dialog_center)
            dialog.setTextSendListener {
                toast(com.starblink.basic.style.R.string.reply_success)
            }
            dialog.setId(item.postComment?.post?.postF?.id!!)
            dialog.setContentType(item.postComment?.post?.postF?.contentType ?: "1")
            dialog.setReplyId(item.postComment?.id!!)
            dialog.setHint("Reply to ${item.friend.userName ?: item.friend.username ?: getString(com.starblink.basic.style.R.string.unknown)}")
            dialog.show()
        }
    }

    override fun initObservable() {
        super.initObservable()
        viewModel.listResponseLiveData.observe(this) {
            if (mAdapter.items.isEmpty() || it.refresh) {
                // 刷新或页面销毁恢复
                mAdapter.submitList(ArrayList(it.totalList))
                if (it.totalList.size < viewModel.curPageNo * MessageLikeOrCommentVM.PAGE_SIZE) {
                    viewBinding.smartRefreshLayout.setNoMoreData(true)
                }
            } else {
                // 加载更多
                mAdapter.addAll(it.pageList)
                if (it.pageList.size < MessageLikeOrCommentVM.PAGE_SIZE) {
                    viewBinding.smartRefreshLayout.setNoMoreData(true)
                }
            }
        }
        viewModel.mLoadActionLiveData.observe(this) {
            when (it.action) {
                LoadAction.STATE_SUCCESS, LoadAction.STATE_ERROR -> {
                    if (viewBinding.smartRefreshLayout.isRefreshing) {
                        viewBinding.smartRefreshLayout.finishRefresh()
                        if (it.action == LoadAction.STATE_SUCCESS) {
                            // 仅刷新成功时，重置状态
                            viewBinding.smartRefreshLayout.resetNoMoreData()
                            mAdapter.isEmptyViewEnable = true
                        }
                    } else if (viewBinding.smartRefreshLayout.isLoading) {
                        viewBinding.smartRefreshLayout.finishLoadMore()
                    }
                }
            }
        }
    }

    override fun initLoad() {
        super.initLoad()
        // 首次打开自动加载
        viewBinding.smartRefreshLayout.autoRefresh()
    }

    companion object {
        const val EXTRA_IS_LIKE_MESSAGE = "EXTRA_IS_LIKE_MESSAGE"

        /**
         * 跳转本页面
         * @param isLikeMessage true表示Like消息页面，false表示评论消息页面
         */
        fun navigation(context: Context, isLikeMessage: Boolean) {
            context.navigationTo(RoutePage.Message.MESSAGE_LIKE_OR_COMMENT) {
                withBoolean(EXTRA_IS_LIKE_MESSAGE, isLikeMessage)
            }
        }
    }
}